﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;

namespace MiReaderLib
{
    class Cmd
    {
        const int STX   = 0x02;
        const int ETX   = 0x03;

        public static byte[] build(params byte[] data)
        {
            int dataLen = data.Length;
            int cmdLen  = dataLen + 5;
            byte[] cmd  = new byte[cmdLen];
            cmd[0] = STX;
            cmd[1] = 1;
            cmd[2] = (byte)dataLen;
            for (int i = 0; i < dataLen; i++)
                cmd[3 + i] = data[i];
            byte BCC = calcCmdChkSum(
                cmd[1], 
                cmd[2], 
                data
            );
            cmd[cmdLen - 2] = BCC;
            cmd[cmdLen - 1] = ETX;
            return cmd;
        }

        public static bool isValidCmd(byte[] cmd)
        {
            int lenCmd = cmd.Length;
            if (lenCmd <= 5)
                return false;
            if (cmd[0] != STX)
                return false;
            if (cmd[2] != (lenCmd - 5))
                return false;
            byte BCC = calcCmdChkSum(
                cmd[1], 
                cmd[2], 
                getCmdData(cmd)
            );
            if (cmd[lenCmd - 2] != BCC)
                return false;
            if (cmd[lenCmd - 1] != ETX)
                return false;
            return true;
        }

        public static byte[] getCmdData(byte[] cmd)
        {
            byte[] data = new byte[cmd.Length - 5];
            Array.Copy (cmd, 3, data, 0, cmd.Length - 5);
            return data;
        }

        static byte calcCmdChkSum(byte stationId, byte len, byte[] data)
        {
            return (byte)(stationId ^ len ^ xorChkSum(data));
        }

        static byte xorChkSum(byte[] buff)
        {
            byte ret = 0;
            foreach (byte b in buff)
                ret ^= b;
            return ret;
        }
    }
}
